﻿<template>
    <div>
        <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
            <el-form :model="obj">
                <el-form-item label="Promotion name" :label-width="formLabelWidth">
                    <el-input v-model="obj.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="Zones" :label-width="formLabelWidth">
                    <el-input v-model="obj.author" autocomplete="off" />
                </el-form-item>
                <el-form-item label="当前文件" :label-width="formLabelWidth">

                    <el-input v-model="obj.files" disabled="false" autocomplete="off" />
                </el-form-item>
                <el-form-item>
                    <el-upload v-model:file-list="fileList" class="upload-demo" action="#" multiple
                        :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="3"
                        :on-exceed="handleExceed" :http-request="postUploadBig">
                        <el-button type="primary">Click to upload</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png files with a size less than 500KB.
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="VTCloseClick(true)">Cancel</el-button>
                    <el-button type="primary" @click="HandleConfirm(obj)">
                        Confirm
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>

import { onMounted, ref, toRef } from 'vue'
import { ElMessage } from 'element-plus';
import { Modify, upload, uploadBig } from '../../../api/table';

const formLabelWidth = ref('140px')
const identifier = ref((new Date()).getTime().toString())
const progress = ref()
//使用了setup，这里便可以直接使用
const props = defineProps({
    obj: {},
    title: '',
    author: '',
    dialogFormVisible: false
})

const emit = defineEmits(["VTClose"]);

const dialogFormVisible = props.dialogFormVisible

onMounted(() => {
    console.log('dialogFormVisible', props.dialogFormVisible)
})

const VTCloseClick = function (val) {
    console.log('子组件准备触发父组件监听事件', val)
    emit('VTClose', !val)
}

const HandleConfirm = async function (obj) {
    console.log('子组件要提交数据了', props.title, props.author)
    var res = await Modify({ id: obj.id, title: obj.title, author: obj.author, files: obj.files })
    if (res && res.code === 20000) {
        ElMessage.success(res.data)
        emit('VTClose', false)
    }
}

const postUpload = async function (file) {
    console.log('上传文件入参', file.file.name)
    let formData = new FormData()
    formData.append('file', file.file)
    var res = await upload(formData)
    if (res && res.code === 20000) {
        debugger
        props.obj.files.push(res.data[0])
        console.log('当前文件列表:', props.obj.files.value)
    }

    console.log("上传文件返回", res)
}
const postUploadBig = async function (file) {
    uploadBigTmp(file.file,0);
}

const uploadBigTmp = async function (file, idx) {
    // 文件切片大小定为1MB
    const bytesPerPiece = 1 * 1024 * 1024;
    let startBytes = idx * bytesPerPiece;
    let endBytes = startBytes + bytesPerPiece;
    if (endBytes > file.size) {
        endBytes = file.size;
    }
    const totalPieces = Math.ceil(file.size / bytesPerPiece)
    // 全部上传完毕后退出
    if (startBytes == file.size) {
        return false;
    }
    // 切割文件，file对象的slice方法，文件分片的核心方法
    const chunk = file.slice(startBytes, endBytes);

    // 定义form对象
    let data = new FormData();
    data.set("chunknumber", idx + 1);
    data.set("chunksize", chunk.size);
    data.set("totalsize", file.size);
    data.set("identifier", identifier.value);
    data.set("filename", file.name);
    data.set("uid", 1);
    data.set("type", 'user');
    data.set("totalChunks", totalPieces);
    data.set("file", new File([chunk], file.name, { type: file.type }));
    // let protemp = parseInt(Math.ceil((100 / totalPieces) * 100) / 100)
    let protemp = parseInt(Math.ceil((100 / totalPieces) * 100) / 100)
    // this.progress = parseInt(100 * startBytes / file.size)
    progress.value = progress.value + protemp
    // this.progress = 100
    // post请求 postForm 为自定义的form表单请求方法
    uploadBig(data).then((res) => {
        // 根据后端返回是否完成
        if (res && res.code === 20000) {
            props.obj.files.push(res.data[0])
            return true;
        }
    }).catch(err => {

    })
    debugger
    if (idx + 1 == totalPieces) return;
    // 上传
    uploadBigTmp(file, ++idx);
}


</script>